package com.lwei.tallybook.service.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lwei.tallybook.base.domain.Account;
import com.lwei.tallybook.service.mapper.AccountMapper;
import com.lwei.tallybook.service.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author sks.lwei
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Override
    public List<Account> listAll() {
        return super.list();
    }

    @Override
    public List<Account> listInUuids(List<String> uuids) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.in("uuid", uuids);
        return super.list(wrapper);
    }

    @Override
    public Account getAccountByUuid(String uuid) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);
        return super.getOne(queryWrapper);
    }

    @Override
    public Account getAccountByName(String name) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", name);
        return super.getOne(queryWrapper);
    }

    @Override
    public boolean validationPassword(Account account, String oldPassword) {
        String passWord = account.getPassWord();
        String md5Hex16 = DigestUtil.md5Hex16(account.getUuid() + oldPassword);
        return md5Hex16.equals(passWord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void changePwd(Account account, String password) {
        String md5Hex16 = DigestUtil.md5Hex16(account.getUuid() + password);
        UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("password", md5Hex16);
        updateWrapper.eq("id", account.getId());
        this.update(updateWrapper);
    }

    public static void main(String[] args) {
        String md5Hex16 = DigestUtil.md5Hex16("user_4" + "111111");
        System.out.println(md5Hex16);
    }
}
